package com.example.demo.controller;

import com.example.demo.model.User;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

// 使用@ResponseBody修饰一个类的时候，表示此类中的所有方法都会返回一个非页面的数据
@ResponseBody
@Controller
@RequestMapping("/user")
public class UserController {

    // 将配置文件中的变量注入
    @Value("${upload.path}")
    private String uploadPath;
    // 看程序启动的时候能不能读取到配置文件的内容
    @PostConstruct
    public void postConstruct(){
        System.out.println();
        System.out.println("upload.path:"+uploadPath);
        System.out.println();
    }

    // 用户和程序的互联互通
    // RequestMapping 既能修饰类，也能修饰方法。路径层次不同

    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    // 默认情况下是返回一个页面
    // 加注解使得返回的是非页面的数据
    public Object syaHi(){
        return "Spring MVC";
    }
    @GetMapping("/get-type")
    public String getType(){
        return "GetMapping";
    }
    @PostMapping("/post-type")
    public String poostType(){
        return "PostMapping";
    }
    // 开始第二个目标
    @GetMapping("/reg")
    // 注意，前端传的参数 命名必须也是 name.
    // 建议将参数设置成包装类型，防止不传参数的时候报错
    public String reg(String name,Integer age){
        return "注册："+name+age;
    }

    @GetMapping("/reg2")
    public Object reg2(@RequestBody User user){
        return user;
    }
    // 重命名前端的key值 极端的情况
    // 设置 required = false 来避免不传递时报错
    @GetMapping("/time")
    public String setTime(@RequestParam(value="time",required = false) String createtime){
        return "时间："+createtime;
    }
    @PostMapping("/p/{name}/{password}")
    public Object param(@PathVariable String name,@PathVariable String password){
        return name+" "+password;
    }
    @RequestMapping("/file")
    public String upload(@RequestPart("myfile") MultipartFile file) throws IOException {
        // 保存文件
        file.transferTo(new File("D:\\test.jpg"));
        return "上传成功";
    }
    @RequestMapping("/file2")
    public String upload2(@RequestPart("myfile") MultipartFile file) throws IOException {
        // 1.上传文件目录（从配置文件中读取）
        String basePath = uploadPath;

        // 2.生成动态的文件名
        String fileName = UUID.randomUUID()+
                (file.getOriginalFilename().substring(
                        file.getOriginalFilename().lastIndexOf(".")
                ));

        file.transferTo(new File(basePath+fileName));
        return "上传成功";
    }
    /**
     * Spring MVC（基于Servlet）所有映射方法中都会内置两个参数：HttpServletRequest HttpServletResponse
     * */
    @RequestMapping("/getCk")
    public Cookie[] getCk(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        return cookies;
    }
    @RequestMapping("/getCk2")
    public String getCk2(@CookieValue("bite") String bite){
        return bite;
    }
    @RequestMapping("/getua")
    public String getUa(@RequestHeader("User-Agent") String userAgent){
        return userAgent;
    }
    /*
    * 仿照用户登录
    * */
    @RequestMapping("/getSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        if(session!=null){
            session.setAttribute("username","ls");
            return "hahah";
        }
        return "用户登录成功";
    }
    /**
     * 验证用户是否登录
     * */
    @RequestMapping("/getSession2")
    public String getSession(HttpServletRequest request){
        String username = "无";
        HttpSession session = request.getSession(false);
        if(session!=null && session.getAttribute("username")!=null){
            username = (String) session.getAttribute("username");
        }
        return username;
    }
    // 更简单的读取Session
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute(value = "username",required = false) String username){
        return username;
    }
    @RequestMapping("/gethtml")
    public String getHtml(String name){
        return "<h1>你好："+name+"</h1>";
    }
}
